// 传入的复制内容
export const copyContent = data => {
  const oInput = document.createElement('input')
  oInput.setAttribute('readonly', '')
  oInput.value = data
  document.body.appendChild(oInput)
  // 选择对象
  oInput.select()
  // 选中全部文本
  oInput.setSelectionRange(0, data.length)
  document.execCommand('Copy') // 执行浏览器复制命令
  oInput.remove()
}

export const formatTime = timestamp => {
  let date = new Date(timestamp * 1000)
  return date.getFullYear() + '.' + addZero(date.getMonth() + 1) + '.' + addZero(date.getDate())
}

function addZero(v) {
  if (v < 10) {
    return '0' + v
  } else {
    return v
  }
}

export const topOffset = el => {
  return el.offsetTop
}

export const debounce = (func, wait) => {
  let timeout
  return function () {
    let context = this
    let args = arguments
    if (timeout) clearTimeout(timeout)

    timeout = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}
export function preLoadImg(urlList) {
  for (let i = 0; i < urlList.length; i++) {
    let img = new Image()
    img.src = urlList[i]
  }
}
export function convertImgToBase64(url, callback) {
  let canvas = document.createElement('CANVAS')
  let ctx = canvas.getContext('2d')
  let img = new Image()
  img.setAttribute('crossOrigin', 'anonymous')
  img.src = url
  img.onload = function () {
    canvas.height = img.height
    canvas.width = img.width
    ctx.drawImage(img, 0, 0)
    var dataURL = canvas.toDataURL('image/jpeg', 0.5)
    callback.call(this, dataURL)
    canvas = null
  }
  img.onerror = function () {
    console.log('onerror')
  }
}


// 给url添加参数
export function addQuery(url, name, value) {
  let mark = '?'
  if (url.indexOf('?') !== -1) {
    mark = '&'
  }
  return url + mark + name + '=' + value
}

// 长按
export function trackingTouch(triggerDOM, cb) {
  let touchStartTimeOut
  triggerDOM.ontouchstart = function () {
    clearTimeout(touchStartTimeOut)
    touchStartTimeOut = setTimeout(function () {
      cb()
    }, 600)
  }
  triggerDOM.ontouchend = function () {
    clearTimeout(touchStartTimeOut)
  }
}